﻿/*****
 *  Copyright 2011, Kaven Gagné
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

using System;
using System.Windows.Data;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;


namespace Knowledge.Resources
{
    /*****
     * Extract the file icon image by extension
     * and returns it as an ImageSource
     */
    [ValueConversion(typeof(String), typeof(System.Windows.Media.ImageSource))]
    public class FileIconConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                // Get a random file name
                string tempFileName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                // Change extension to the right one
                tempFileName = Path.ChangeExtension(tempFileName, Path.GetExtension((string)value));
                File.Create(tempFileName).Close();
                System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(tempFileName);
                if (icon != null)
                {
                    System.Drawing.Bitmap bitmap = icon.ToBitmap();
                    IntPtr hBitmap = bitmap.GetHbitmap();
                    File.Delete(tempFileName);
                    return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                }
            }
            catch (Exception e)
            {
                //If it fails, Use IconFileBlank.png
                Utilities.PrintError(e);
            }
            return new BitmapImage(new Uri("/Knowledge;component/Images/IconFileBlank.png", UriKind.Relative));
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }

}